package com.fingard.dsp.bank.directbank.zyb01;

import java.util.Calendar;
import java.util.Date;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

public class ZYB01Transaction extends ZYB01Base implements ITransaction {

	//���������?ʽ
	//1��ѭ������readRecord()��ȡһ��������ϸ��Ȼ��д�뷢���е�XML����
	//2��������
	//3��ѭ������XmlTextReader.read()��ȡһ�����з��ؽڵ㣬��ֵ����ATS����ϸ����
	//   Ȼ�����writeRetDetail()��д�뷵��ATS����ϸ
	public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception{
		//��ʷ��ϸ��ѯ����ATS�Ķ���
		RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
		String tmpRespCode = "";
		String tmpRespInfo = "";
		String sigData="0";
		String charsetName = "GBK";
		retAts.writeStart();//д����ATS��ͳһͷ����Ϣ
		try {
			ZYB01Header tmpBankHeader = new ZYB01Header();
			tmpBankHeader.trsCode = "05B2EActTrsQry";

			//tmpClndrStepTo.get(Calendar.MONTH) MONTH�Ǵ�0��ʼ��ģ���ζ��0��1�£�11��12��
			Calendar tmpCalendarFrom = Calendar.getInstance();
			tmpCalendarFrom.setTime(p_req7516.getDateFrom());
			
			Calendar tmpCalendarTo = Calendar.getInstance();
			tmpCalendarTo.setTime(p_req7516.getDateTo());
				
				int tmpNowStartRecord = 0;//��ѯ��¼��ʼ��
				int intPageNumber = -1;//��ѯ��¼��
                int tmpNowReadedCount = 0;

				boolean tmpQryNext = true;
				while(tmpQryNext && tmpRespCode.length() == 0){//��ҳ��ѯ
					XmlTextWriter xmlWriter = new XmlTextWriter();//�����б��ĵ�XML����
					//д��ͨ�õ�ͷ���ڵ�
					writeCommonHeader(xmlWriter, tmpBankHeader,reqHeader.transSeqID);
					/*<Body>
					<AcNo>8015014000000004444</AcNo>
					<Currency>CNY</Currency>
					<BeginDate>20170501</BeginDate>
					<EndDate>20170527</EndDate>
					<Total_Num>0</Total_Num>
					<Current_Num>10</Current_Num>
					</Body>
					</Message>*/
					xmlWriter.writeStartElement("Body");
					xmlWriter.writeElementString("AcNo", p_req7516.actNum);
					xmlWriter.writeElementString("Currency",convertCurToBank(p_req7516.actCur));
					xmlWriter.writeElementString("BeginDate", Format.Date8Format.format(tmpCalendarFrom.getTime()));
					xmlWriter.writeElementString("EndDate", Format.Date8Format.format(tmpCalendarTo.getTime()));
					xmlWriter.writeElementString("Total_Num", String.valueOf(intPageNumber));
					xmlWriter.writeElementString("Current_Num", String.valueOf(tmpNowStartRecord));
					xmlWriter.writeEndElement();
					xmlWriter.writeEndDocument();
					String[] tmpStrRet = sendToBank(xmlWriter.toXmlString(),tmpBankHeader,sigData,charsetName);
					XmlTextReader tmpBkReader;
					if(tmpStrRet[0].length() == 0){
						StringBuilder tmpSbMsg = new StringBuilder();
						tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
						if(tmpBkReader != null){
							/*<?xml version="1.0" encoding="UTF-8"?>
							<Reply_Msg>
							<Sys_Head>
							<ReturnCode>000000</ReturnCode>
							<ReturnMsg></ReturnMsg>
							</Sys_Head>
							<Body>
							<RecordNumber>4</RecordNumber>
							<List>
							<Row>
							<TransDate>2017-05-05</TransDate>
							<TransTime>10:50:59</TransTime>
							<EffectDate>2017-05-05</EffectDate>
							<Currency>CNY</Currency>
							<DCFlag>D</DCFlag>
							<Amount>83.74</Amount>
							<Balance>119564.79</Balance>
							<Remark></Remark>
							<OtherAcNo>411099010980000055</OtherAcNo>
							<OtherName></OtherName>
							<OthBankName></OthBankName>
							<TranDesc></TranDesc>
							<TrsChannel>CB</TrsChannel>
							<Reference>BTE21072700105780200</Reference>

							</Row>
							</List>
							</Body>
							</Reply_Msg>*/
							String returnCode = tmpBkReader.getFirstText("/Reply_Msg/Sys_Head/ReturnCode");
							String returnMsg = tmpBkReader.getFirstText("/Reply_Msg/Sys_Head/ReturnMsg");
							if (isActiveRetCode(returnCode)){
								int tmpTotalRocords = 0;
		                        if (tmpBkReader.getFirstText("/Reply_Msg/Body/RecordNumber") != null && tmpBkReader.getFirstText("/Reply_Msg/Body/RecordNumber").trim().length() > 0)
		                        {
		                            tmpTotalRocords = Integer.parseInt(tmpBkReader.getFirstText("/Reply_Msg/Body/RecordNumber"));
		                        }
		                        int tmpEachPiCount = 0;
		                        while(tmpBkReader.read("/Reply_Msg/Body/List/Row")){
		                        	tmpEachPiCount++;
									RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();
									tmpRetDetail.recAccBank = tmpBkReader.readedXElement.getSingleText("OthBankName");
									tmpRetDetail.recAccNum  = tmpBkReader.readedXElement.getSingleText("OtherAcNo");
                                    tmpRetDetail.recAccName = tmpBkReader.readedXElement.getSingleText("OtherName");
									tmpRetDetail.cur = tmpBkReader.readedXElement.getSingleText("Currency");
                                    String creditDebitFlag = tmpBkReader.readedXElement.getSingleText("DCFlag");
                                    String tranAmount = tmpBkReader.readedXElement.getSingleText("Amount");
                                    if (creditDebitFlag != null){
                                        if (creditDebitFlag.equals("D")) //����ʶ
                                        {
                                            if (tranAmount.indexOf("-")>=0)
                                            {
                                            	tmpRetDetail.cdFlag = "2";
                                            }
                                            else
                                            {
                                            	tmpRetDetail.cdFlag = "1";
                                            }
                                        }
                                        else
                                        {
                                            if (tranAmount.indexOf("-")>=0)
                                            {
                                            	tmpRetDetail.cdFlag = "1";
                                            }
                                            else
                                            {
                                            	tmpRetDetail.cdFlag = "2";
                                            }
                                        }
                                    }
                                    tmpRetDetail.tranAmt = tranAmount.replace("-", "");
                                    /*tmpRetDetail.originator = tmpBkReader.readedXElement.getSingleText("tranNo").trim();*/
                                    tmpRetDetail.accBal = tmpBkReader.readedXElement.getSingleText("Balance").trim();//���
                                    
                                    String tranDate = tmpBkReader.readedXElement.getSingleText("TransDate");
                                    String tranTime = tmpBkReader.readedXElement.getSingleText("TransTime");
                                    String effectDate= tmpBkReader.readedXElement.getSingleText("EffectDate");//��Ч����
                                    tmpRetDetail.tranDate = tranDate;
                                    if(StringHelper.hasAnyChar(tranTime)){
                                    	tmpRetDetail.tranTime = tmpRetDetail.tranDate + " " + tranTime;
                                    }
                                    else{
                                    	tmpRetDetail.tranTime = tmpRetDetail.tranDate;
                                    }
                                    if(StringHelper.hasAnyChar(effectDate)){
                                    	tmpRetDetail.valueDate = effectDate;
                                    }
                                    else{
                                    	tmpRetDetail.valueDate = tmpRetDetail.tranDate;
                                    }
                                    tmpRetDetail.usage = tmpBkReader.readedXElement.getSingleText("TranDesc");
                                    tmpRetDetail.abstr = pickupAbstr(tmpRetDetail.usage);
                                    /*tmpRetDetail.comment = tmpBkReader.readedXElement.getSingleText("sumTranNo");*/
                                    tmpRetDetail.payCode = tmpBkReader.readedXElement.getSingleText("Reference");//ҵ��ο���
                                    
									if(StringHelper.isNullOrEmpty(tmpRetDetail.actNum)){
										tmpRetDetail.actNum = p_req7516.actNum;
									}
									
									retAts.writeRetDetail(tmpRetDetail);
								}
		                        tmpNowReadedCount += tmpEachPiCount;//�ܼ�¼��
		                        if (tmpEachPiCount != tmpTotalRocords)
		                        {
									tmpQryNext = false;
		                            tmpRespCode = "-1";
									tmpRespInfo = "����Ԥ�ڷ���" + tmpTotalRocords + "����ʵ�ʶ�ȡ" + tmpEachPiCount+"��";
		                            break;
		                        }
		                        if (tmpNowReadedCount < tmpTotalRocords)//��ѯ��һҳ
		                        {
		                            tmpNowStartRecord = tmpNowReadedCount + 1;//���η�ҳ��ҳ��ѯ��ʼ��¼��
		                        }
		                        else if (tmpNowReadedCount == tmpTotalRocords)//���η�ҳ��ѯ���
		                        {
									    tmpQryNext=false;
		                                tmpNowStartRecord = 0;
		                                tmpNowReadedCount = 0;
		                                continue;
		                        }
							}
							else{
								tmpQryNext = false;
								tmpRespCode = "-1";
								tmpRespInfo = returnMsg;
								break;
							}
						}
						else{
							tmpQryNext = false;
							tmpRespCode = "-1";
							tmpRespInfo = tmpSbMsg.toString();
							break;
						}
					}
					else{
						tmpQryNext = false;
						tmpRespCode = "-1";
						tmpRespInfo = tmpStrRet[1];
						break;
					}
				}
		} catch (Exception e) {
			tmpRespCode = "-1";
			tmpRespInfo = e.getMessage();
			e.printStackTrace();
		}
		if(tmpRespCode.equals("-1")){
			retAts = new RetAtsTrans(p_req7516.reqHeader);
			retAts.writeStart();//д����ATS��ͳһͷ����Ϣ
			retAts.writeRespCode(tmpRespCode);
			retAts.writeRespInfo(tmpRespInfo);
		}
		else if(retAts.getWrittenRdCount() == 0){
			retAts.writeRespCode("0");
			retAts.writeRespInfo("����Ϊ��");
		}
		retAts.writeEnd();
		return retAts;
	}

	//������ϸ��ѯ������ʷ��ϸ��ѯ����
	public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception{
		//ͨ��b2e0035
		Req7516HisTrans tmpReq7516 = new Req7516HisTrans(p_req7515.reqHeader);
		tmpReq7516.actArea = p_req7515.actArea;
		tmpReq7516.actCur = p_req7515.actCur;
		tmpReq7516.actNum = p_req7515.actNum;
		String tmpStrToday = Format.Date8Format.format(new Date());
		tmpReq7516.dateFrom = tmpStrToday;
		tmpReq7516.dateTo = tmpStrToday;
		return 	d_7516_HisTrans(tmpReq7516);
	}
}
